﻿#pragma execution_character_set("utf-8")

#include <QJsonObject>
#include <QJsonDocument>
#include <QDateTime>
#include <QMessageBox>
#include <QCryptographicHash>

#include "register.h"
#include "ui_register.h"
#include "requests.h"


Register::Register(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Register)
{
    ui->setupUi(this);
    hide();
}

Register::~Register()
{
    delete ui;
}

void Register::on_toolButton_clicked()
{
    // 从界面上获取注册信息
    auto user = ui->edit_user->text();
    auto passwd = ui->edit_password->text();
    auto phone = ui->edit_phone->text();
    auto email = ui->edit_email->text();
    QString passwd_md5 = QCryptographicHash::hash(passwd.toLocal8Bit(), QCryptographicHash::Md5);
    qInfo() << passwd_md5 << passwd_md5.length();

    if(user.isEmpty()) {
        QMessageBox::warning(this, "警告", "用户名不能为空");
        return;
    }
    if(passwd.isEmpty()) {
        QMessageBox::warning(this, "警告", "密码不能为空");
        return;
    }
    if(phone.isEmpty()) {
        QMessageBox::warning(this, "警告", "手机号不能为空");
        return;
    }
    if(email.isEmpty()) {
        QMessageBox::warning(this, "警告", "邮箱不能为空");
        return;
    }

    auto date = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QJsonObject obj = {{"user", user}, {"password", passwd_md5}, {"phone", phone}, {"email", email}, {"date", date}};
    auto str = QJsonDocument(obj).toJson(QJsonDocument::Compact).toBase64().toStdString();
    auto resp = requests::post("192.168.2.138:8080/register", str.c_str());
    if (resp == NULL) {
        qInfo() << "request failed!\n";
    }
    else {
        auto str = QByteArray::fromBase64(resp->body.c_str());
        qInfo() << str;
        QJsonObject respObj = QJsonDocument::fromJson(str).object();
        if(respObj.contains("result") && respObj["result"].toBool()) {
            QMessageBox::information(this, "提示", "恭喜你注册成功");
        }
        else {
            QMessageBox::warning(this, "警告", "注册失败");
        }
    }
}

